#!/usr/bin/env python
#-*- coding: utf-8 -*-

"""
    Copyright 2010, 2011, 2012 Kacper Żuk <kacper.b.zuk@gmail.com>
    
    This file is part of Urh Dungeon 2.

    Urh Dungeon 2 is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Urh Dungeon 2 is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Urh Dungeon 2.  If not, see <http://www.gnu.org/licenses/>.
"""

import pygame, sprites, vars, sys, colors, os
from copy import copy
from functions import *
from pygame.locals import *

FPS = 15

class Gui():
    def __init__(self):
        self.items = {}

    def createWidgets(self, current):
        self.items = {}
        x = 22*32+140
        w = 110
        self.items["dung.floor"] = Input((22*32+70, 22*32-23, 55, 15), "dung.floor", vars.dung.floor)
        if current:
            self.items["type"] = Input((x, 190, w, 15), "type", current.type)
            self.items["sprite"] = Input((x, 205, w, 15), "sprite", current.sprite)
            if current.type == "char":
                self.items["name"] = Input((x, 220, w, 15), "name", current.name)
                self.items["lvl"] = Input((x, 235, w, 15), "lvl", str(current.lvl))
                self.items["hp"] = Input((x, 250, w, 15), "hp", str(current.hp))
                self.items["dex"] = Input((x, 265, w, 15), "dex", str(current.dex))
                self.items["str"] = Input((x, 280, w, 15), "str", str(current.str))
                self.items["exp"] = Input((x, 295, w, 15), "exp", str(current.exp))
            elif current.type == "msgNpc":
                self.items["name"] = Input((x, 220, w, 15), "name", current.name)
                self.items["msg"] = Input((x, 235, w, 15), "msg", current.msg)
            elif current.type == "chest":
                self.items["item.name"] = Input((x, 220, w, 15), "item.name", current.item.name)
                self.items["item.str"] = Input((x, 235, w, 15), "item.str", str(current.item.str))
                self.items["item.dex"] = Input((x, 250, w, 15), "item.dex", str(current.item.dex))
                self.items["item.type"] = Input((x, 265, w, 15), "item.type", current.item.type)
                self.items["item.power"] = Input((x, 280, w, 15), "item.power", str(current.item.power))
            elif current.type == "portal":
                self.items["dest"] = Input((x, 220, w, 15), "dest", str(current.dest))
                self.items["destpos"] = Input((x, 235, w, 15), "destpos", str(current.destpos))
            elif current.type == "wall":
                self.items["transparent"] = Input((x, 220, w, 15), "transparent", current.transparent)
            elif current.type == "lock":
                xi = 0
                self.items["name"] = Input((x, 220, w, 15), "name", current.name)
                if current.rep.type in ("floor", "wall", "portal"):
                    self.items["rep.type"] = Input((x, 235, w, 15), "rep.type", current.rep.type)
                    self.items["rep.sprite"] = Input((x, 250, w, 15), "rep.sprite", current.rep.sprite)
                    if current.rep.type == "portal":
                        xi += 2
                        self.items["rep.dest"] = Input((x, 265, w, 15), "rep.dest", str(current.rep.dest))
                        self.items["rep.destpos"] = Input((x, 280, w, 15), "rep.destpos", str(current.rep.destpos))
                    self.items["ob"] = Input((x, 265+xi*15, w, 15), "ob", str(current.ob), True)
        else:
            self.items["type"] = Input((x, 190, w, 15), "type", "False")
        
    def update(self, events, current):
        for item in self.items.values():
            item.update(events)

    def draw(self, dest):
        for item in self.items.values():
            item.draw(dest)

    def getData(self, id=None):
        if id:
            if self.items.__contains__(id):
                return self.items[id].text
            return None
        else:
            data = {}
            for item in self.items.values():
                data[item.id] = item.text
            return data
        
class Input():
    def __init__(self, rect, id, text="", fit=None):
        self.rect = pygame.Rect(rect)
        self.id = id
        self.fit = fit
        self.text = text
        self.focus = False
        
    def update(self, events):
        for ev in events:
            if isinstance(self.text, bool):
                if ev.type == MOUSEBUTTONDOWN:
                    if self.rect.collidepoint(ev.pos):
                        self.text = not self.text
            elif ev.type == MOUSEBUTTONDOWN:
                if self.rect.collidepoint(ev.pos):
                    self.focus = True
                else:
                    self.focus = False
            elif self.focus and ev.type == KEYDOWN:
                if ev.key == K_RETURN:
                    self.focus = False
                    continue
                bla = pygame.key.get_pressed()
                if len(pygame.key.name(ev.key)) > 1 and not (pygame.key.name(ev.key) == "backspace" or pygame.key.name(ev.key) == "space"):
                    return
                elif pygame.key.name(ev.key) == "backspace":
                    key = "backspace"
                elif bla[304]:
                    if chr(ev.key) == '0':
                        key = ")"
                    elif chr(ev.key) == '9':
                        key = "("
                    elif chr(ev.key) == '=':
                        key = '+'
                    elif chr(ev.key) == '8':
                        key = '*'
                    elif chr(ev.key) == '-':
                        key = '_'
                    else:
                        key = chr(ev.key-32)
                else:
                    key = chr(ev.key)
                if key == "backspace":
                    if self.text > 0:
                        self.text = self.text[:-1]
                else:
                    self.text += key

    def draw(self, dest):
        if self.fit:
            font = pygame.font.Font(vars.font, 10)
            rect = copy(self.rect)
            rect.w -= 5
            lines = fitInRect(str(self.text), font, self.rect)
            x = 0
            for line in lines:
                rect = copy(self.rect)
                rect.h = 15
                rect.y += 15*x
                if self.focus:
                    pygame.draw.rect(dest, colors.green, rect)
                else:
                    pygame.draw.rect(dest, colors.grey, rect)
                printSurface(dest, line, 10, colors.black, (self.rect.x+5, rect.y))
                x += 1
            self.rect.h = x*15
        else:
            if self.focus:
                pygame.draw.rect(dest, colors.green, self.rect)
            else:
                pygame.draw.rect(dest, colors.grey, self.rect)
            printSurface(dest, str(self.text), 10, colors.black, (self.rect.x+5, self.rect.y))
                 
        
class Cam():
    def __init__(self):
        self.x = 0
        self.y = 0
        
class Editor():
    def __init__(self):
        pygame.init()
        pygame.display.set_icon(img('icon'))
        self.okienko = pygame.display.set_mode((30*32, 22*32))
        pygame.display.set_caption('Urh Dungeon 2 - Editor')
        pygame.key.set_repeat(400,50)
        self.clock = pygame.time.Clock()
        self.cam = Cam()
        self.tab = 0
        self.gui = Gui()
        vars.dung = sprites.dungeon()
        vars.dung.regenerate()
        self.current = False
        self.gui.createWidgets(self.current)
        self.box = False
        self.loop()

    def save(self):
        os.rename('dungs.upf', 'dungs.bak') #backup
        cPickle.dump(vars.dung.dungeons, open('dungs.upf', 'w'))

    def drawDung(self):
        xoff = 352 - self.cam.x*32
        yoff = 352 - self.cam.y*32
        self.okienko.blit(vars.dung.img, (0, 0), (-xoff,-yoff,704, 704))

    def drawTabs(self):
        tabs = pygame.Surface((22*32, 25))
        for x in range(len(vars.dung.dungeons)):
            #[scrolling]
            co = 0
            if self.tab > 25:
                co = self.tab-25
            #[/scrolling]
            if x+co == self.tab:
                printSurface(tabs, str(x+co), 10, colors.red, (27+(x+1)*20,10), True)
            else:
                printSurface(tabs, str(x+co), 10, colors.white, (27+(x+1)*20,10), True)
            pygame.draw.line(tabs, (111,111,111), (37+(x+1)*20, 0), (37+(x+1)*20,25), 2)
            if 37+(x+2)*20 > 22*32-135:
                break
        pygame.draw.line(tabs, (111,111,111), (0, 23), (22*32,23), 2)
        printSurface(tabs, "Back", 10, colors.white, (3,3))
        pygame.draw.line(tabs, (111,111,111), (35, 0), (35,25), 2)
        printSurface(tabs, "Next", 10, colors.white, (22*32-125,3))
        pygame.draw.line(tabs, (111,111,111), (22*32-135, 0), (22*32-135,25), 2)
        printSurface(tabs, "New", 10, colors.white, (22*32-80,3))
        pygame.draw.line(tabs, (111,111,111), (22*32-90, 0), (22*32-90,25), 2)
        printSurface(tabs, "Delete", 10, colors.white, (22*32-40,3))
        pygame.draw.line(tabs, (111,111,111), (22*32-50, 0), (22*32-50,25), 2)
        self.okienko.blit(tabs, (0,0))
        
    def drawPanel(self):
        pygame.draw.line(self.okienko, (111,111,111), (22*32, 0), (22*32,22*32), 2)
        printSurface(self.okienko, "Hover", 15, colors.white, (22*32+8*16, 10), True)
        pygame.draw.line(self.okienko, (111,111,111), (22*32, 23), (30*32,23), 2)
        pygame.draw.line(self.okienko, (111,111,111), (22*32, 160), (30*32,160), 2)
        printSurface(self.okienko, "Current", 15, colors.white, (22*32+8*16, 170), True)
        pygame.draw.line(self.okienko, (111,111,111), (22*32, 183), (30*32,183), 2)
        pygame.draw.line(self.okienko, (111,111,111), (22*32, 330), (30*32,330), 2)
        printSurface(self.okienko, "Help", 15, colors.white, (22*32+8*16, 340), True)
        pygame.draw.line(self.okienko, (111,111,111), (22*32, 353), (30*32,353), 2)
        pos = pygame.mouse.get_pos()
        xoff = 352 - self.cam.x*32
        yoff = 352 - self.cam.y*32
        x = (pos[0] - xoff)/32 
        y = (pos[1] - yoff)/32

        printSurface(self.okienko, "dung.width: "+str(len(vars.dung.dung[0])), 10, colors.white, (22*32+5, 22*32-53))
        printSurface(self.okienko, "dung.height: "+str(len(vars.dung.dung)), 10, colors.white, (22*32+5, 22*32-38))
        printSurface(self.okienko, "dung.floor: ", 10, colors.white, (22*32+5, 22*32-23))
        ######## HOVER ##########
        if x in range(len(vars.dung.dung[0])) and y in range(len(vars.dung.dung)) and pos[0] < 22*32 and pos[1] > 25:
            ob = vars.dung.get(x,y)
            printSurface(self.okienko, "x: "+str(x), 10, colors.white, (30*32-60, 30))
            printSurface(self.okienko, "y: "+str(y), 10, colors.white, (30*32-60, 45))
            if ob:
                printSurface(self.okienko, "Hover.type: "+ob.type, 10, colors.white, (22*32+15, 30))
                printSurface(self.okienko, "Hover.sprite: "+ob.sprite, 10, colors.white, (22*32+15, 45))
                if ob.type == "char":
                    printSurface(self.okienko, "Hover.name: "+ob.name, 10, colors.white, (22*32+15, 60))
                    printSurface(self.okienko, "Hover.lvl: "+str(ob.lvl), 10, colors.white, (22*32+15, 75))
                    printSurface(self.okienko, "Hover.hp: "+str(ob.hp), 10, colors.white, (22*32+15, 90))
                    printSurface(self.okienko, "Hover.dex: "+str(ob.dex), 10, colors.white, (22*32+15, 105))
                    printSurface(self.okienko, "Hover.str: "+str(ob.str), 10, colors.white, (22*32+15, 120))
                elif ob.type == "wall":
                    printSurface(self.okienko, "Hover.transparent: "+str(ob.transparent), 10, colors.white, (22*32+15, 60))
                elif ob.type == "msgNpc":
                    printSurface(self.okienko, "Hover.name: "+ob.name, 10, colors.white, (22*32+15, 60))
                    printSurface(self.okienko, "Hover.msg: "+ob.msg, 10, colors.white, (22*32+15, 75))
                elif ob.type == "chest":
                    printSurface(self.okienko, "Hover.item.name: "+ob.item.name, 10, colors.white, (22*32+15, 60))
                    printSurface(self.okienko, "Hover.item.str: "+str(ob.item.str), 10, colors.white, (22*32+15, 75))
                    printSurface(self.okienko, "Hover.item.dex: "+str(ob.item.dex), 10, colors.white, (22*32+15, 90))
                    printSurface(self.okienko, "Hover.item.type: "+ob.item.type, 10, colors.white, (22*32+15, 105))
                    printSurface(self.okienko, "Hover.item.power: "+str(ob.item.power), 10, colors.white, (22*32+15, 120))
                elif ob.type == "portal":
                    printSurface(self.okienko, "Hover.dest: "+str(ob.dest), 10, colors.white, (22*32+15, 60))
                    printSurface(self.okienko, "Hover.destpos: "+str(ob.destpos), 10, colors.white, (22*32+15, 75))
                elif ob.type == "lock":
                    printSurface(self.okienko, "Hover.name: "+ob.name, 10, colors.white, (22*32+15, 60))
                    x = 0
                    if ob.rep.type in ("floor", "wall", "portal"):
                        printSurface(self.okienko, "Hover.rep.type: "+str(ob.rep.type), 10, colors.white, (22*32+15, 75))
                        printSurface(self.okienko, "Hover.rep.sprite: "+str(ob.rep.sprite), 10, colors.white, (22*32+15, 90))
                        if ob.rep.type == "portal":
                            x+=2
                            printSurface(self.okienko, "Hover.rep.dest: "+str(ob.rep.dest), 10, colors.white, (22*32+15, 105))
                            printSurface(self.okienko, "Hover.rep.destpos: "+str(ob.rep.destpos), 10, colors.white, (22*32+15, 120))
                        printSurface(self.okienko, "Hover.ob: "+str(ob.ob), 10, colors.white, (22*32+15, 105+x*15))
                elif ob.type == "bigSprite":
                    printSurface(self.okienko, "Hover.parent.x: "+str(ob.parent.x), 10, colors.white, (22*32+15, 60))
                    printSurface(self.okienko, "Hover.parent.y: "+str(ob.parent.y), 10, colors.white, (22*32+15, 75))
            else:
                printSurface(self.okienko, "Hover: False", 10, colors.white, (22*32+15, 30))


        ######## CURRENT ##########
        ob = self.current
        if ob:
            printSurface(self.okienko, "Current.type: ", 10, colors.white, (22*32+15, 190))
            if not ob.type == 'bigSprite':
                printSurface(self.okienko, "Current.sprite: ", 10, colors.white, (22*32+15, 205))
            if ob.type == "char":
                printSurface(self.okienko, "Current.name: ", 10, colors.white, (22*32+15, 220))
                printSurface(self.okienko, "Current.lvl: ", 10, colors.white, (22*32+15, 235))
                printSurface(self.okienko, "Current.hp: ", 10, colors.white, (22*32+15, 250))
                printSurface(self.okienko, "Current.dex: ", 10, colors.white, (22*32+15, 265))
                printSurface(self.okienko, "Current.str: ", 10, colors.white, (22*32+15, 280))
                printSurface(self.okienko, "Current.exp: ", 10, colors.white, (22*32+15, 295))
            elif ob.type == "msgNpc":
                printSurface(self.okienko, "Current.name: ", 10, colors.white, (22*32+15, 220))
                printSurface(self.okienko, "Current.msg: ", 10, colors.white, (22*32+15, 235))
            elif ob.type == "wall":
                printSurface(self.okienko, "Current.transparent: ", 10, colors.white, (22*32+15, 220))
            elif ob.type == "chest":
                printSurface(self.okienko, "Current.item.name: ", 10, colors.white, (22*32+15, 220))
                printSurface(self.okienko, "Current.item.str: ", 10, colors.white, (22*32+15, 235))
                printSurface(self.okienko, "Current.item.dex: ", 10, colors.white, (22*32+15, 250))
                printSurface(self.okienko, "Current.item.type: ", 10, colors.white, (22*32+15, 265))
                printSurface(self.okienko, "Current.item.power: ", 10, colors.white, (22*32+15, 280))
            elif ob.type == "portal":
                printSurface(self.okienko, "Current.dest: ", 10, colors.white, (22*32+15, 220))
                printSurface(self.okienko, "Current.destpos: ", 10, colors.white, (22*32+15, 235))
            elif ob.type == "lock":
                printSurface(self.okienko, "Current.name: ", 10, colors.white, (22*32+15, 220))
                x = 0
                if ob.rep.type in ("floor", "wall", "portal"):
                    printSurface(self.okienko, "Current.rep.type: ", 10, colors.white, (22*32+15, 235))
                    printSurface(self.okienko, "Current.rep.sprite: ", 10, colors.white, (22*32+15, 250))
                    if ob.rep.type == "portal":
                        x += 2
                        printSurface(self.okienko, "Current.rep.dest: ", 10, colors.white, (22*32+15, 265))
                        printSurface(self.okienko, "Current.rep.destpos: ", 10, colors.white, (22*32+15, 280))
                    printSurface(self.okienko, "Current.ob: ", 10, colors.white, (22*32+15, 265+x*15))
            elif ob.type == "bigSprite":
                printSurface(self.okienko, "Current.parent.x: ", 10, colors.white, (22*32+15, 205))
                printSurface(self.okienko, "Current.parent.y: ", 10, colors.white, (22*32+15, 220))
        else:
            printSurface(self.okienko, "Current:", 10, colors.white, (22*32+15, 190))

        #### BUTTONS ####
        pygame.draw.line(self.okienko, (111,111,111), (22*32+125, 22*32-30), (30*32,22*32-30), 2)
        pygame.draw.line(self.okienko, (111,111,111), (22*32, 22*32-60), (30*32,22*32-60), 2)
        pygame.draw.line(self.okienko, (111,111,111), (22*32, 22*32-90), (30*32,22*32-90), 2)
        pygame.draw.line(self.okienko, (111,111,111), (22*32+125, 22*32-30*3), (22*32+125,22*32), 2)
        buttons = ["Quit", "Reload", "Save"]
        for i in range(3):
            printSurface(self.okienko, buttons[i], 20, colors.white, (894, 22*32-15-30*i), True)
        printSurface(self.okienko, "Set Object", 20, colors.white, (894-128, 22*32-75), True)

        ### HELP ###
        rect = pygame.Rect(22*32+10, 353+5, 30*32-22*32-20, 241)
        helpmsg = "Left mouse button - place current object\n"
        helpmsg += "Right mouse button - copy selected object to current\n"
        helpmsg += "Middle mouse button - resize dungeon\n"
        helpmsg += "Arrows, w, s, a, d - move camera\n"
        helpmsg += "Available types of objects:\n"
        helpmsg += "    False - black area (like Wall with black sprite)\n"
        helpmsg += "    floor - player can move on this object\n"
        helpmsg += "    wall - player can't move on this object\n"
        helpmsg += "    portal - moves player to dest, destpos\n"
        helpmsg += "    char - enemy\n"
        helpmsg += "    lock - it's replaced with .rep when all .ob is dead\n"
        helpmsg += "    msgNpc - simple message showing object\n"
        helpmsg += "    pot - hp potion\n"
        helpmsg += "    chest - object containing item\n"
        helpmsg += "See README.txt for more detailed help, list of attributes and webpage."
        font = pygame.font.Font(vars.font, 9)
        fitInRect(helpmsg, font, rect)
        msg = list()
        for line in helpmsg.split("\n"):
            msg.append(fitInRect(line,font,rect))
        helpmsg = list()
        for proline in msg:
            if isinstance(proline, list):
                for line in proline:
                    helpmsg.append(line)
        x = 0
        for line in helpmsg:
            printSurface(self.okienko, line, 9, colors.white, (rect.x, rect.y+x*13))
            x += 1
        
    def exit(self):
        pygame.quit()
        sys.exit()
        
    def events(self):
        evl = pygame.event.get()
        self.gui.update(evl, self.current)
        for ev in evl:
            if ev.type == QUIT:
                self.exit()
            elif ev.type == KEYDOWN:
                if ev.key in (K_q, K_ESCAPE):
                    self.exit()
                elif ev.key in (K_UP, K_w):
                    if self.cam.y > 0:
                        self.cam.y -= 1
                elif ev.key in (K_DOWN, K_s):
                    if self.cam.y < 1024:
                        self.cam.y += 1
                elif ev.key in (K_LEFT, K_a):
                    if self.cam.x > 0:
                        self.cam.x -= 1
                elif ev.key in (K_RIGHT, K_d):
                    if self.cam.x < 1024:
                        self.cam.x += 1
                elif ev.key == K_RETURN:
                    self.setCurrent()
                    self.gui.createWidgets(self.current)
                elif ev.key == K_t:
                    self.save()
            elif ev.type == MOUSEBUTTONDOWN:
                self.setCurrent()
                self.mouse(ev.pos, ev.button)
            elif ev.type == MOUSEMOTION:
                if pygame.mouse.get_pressed()[0]:
                    xoff = 352 - self.cam.x*32
                    yoff = 352 - self.cam.y*32
                    x = (ev.pos[0] - xoff)/32 
                    y = (ev.pos[1] - yoff)/32
                    try:
                        if not self.current == vars.dung.get(x,y):
                            self.mouse(ev.pos, 1)
                    except IndexError:
                        pass

    def setCurrent(self):
        data = self.gui.getData()
        # Default datas:
        datas = {
                    "name": "",
                    "sprite": "black",
                    "lvl": 1,
                    "hp": 10,
                    "dex": 10,
                    "str": 10,
                    "exp": 10,
                    "msg": "",
                    "item.name": "",
                    "item.power": 10,
                    "item.str": 10,
                    "item.dex": 10,
                    "item.sprite": "",
                    "item.type": "weapon",
                    "dest": 0,
                    "destpos": "(1,1)",
                    "rep.type": "floor",
                    "rep.sprite": "floor1",
                    "rep.dest": 0,
                    "rep.destpos": "(1,1)",
                    "ob": "[(1,1),(2,2),(3,3)]",
                    "transparent": False,
                }
        vars.dung.floor = data['dung.floor']
        vars.dung.regenerate()
        for k, v in datas.iteritems():
            try:
                data[k]
            except KeyError:
                data[k] = v
        if data['type'].lower() == "false":
            self.current = False
        elif data['type'].lower() == "wall":
            self.current = sprites.wall(data['sprite'], data['transparent'])
        elif data['type'].lower() == "floor":
            self.current = sprites.floor(data['sprite'])
        elif data['type'].lower() == "pot":
            self.current = sprites.potion(data['sprite'])
        elif data['type'].lower() == "char":
            self.current = sprites.char(data['name'], data['sprite'])
            self.current.lvl = int(data['lvl'])
            self.current.hp = int(data['hp'])
            self.current.dex = int(data['dex'])
            self.current.str = int(data['str'])
            self.current.exp = int(data['exp'])
        elif data['type'].lower() == "msgnpc":
            self.current = sprites.msgNpc(data['name'], data['sprite'], data['msg'])
        elif data['type'].lower() == "chest":
            self.current = sprites.chest(sprites.item(data['item.name'], int(data['item.power']), int(data['item.str']), int(data['item.dex']), data['item.sprite'], data['item.type']),data['sprite'])
        elif data['type'].lower() == "portal":
            self.current = sprites.portal(data['sprite'], int(data['dest']),eval(data['destpos']))
        elif data['type'].lower() == "lock":
            if data['rep.type'].lower() == "floor":
                rep = sprites.floor(data['rep.sprite'])
            elif data['rep.type'].lower() == "wall":
                rep = sprites.wall(data['rep.sprite'])
            elif data['rep.type'].lower() == "portal":
                rep = sprites.portal(data['rep.sprite'], int(data['rep.dest']), eval(data["rep.destpos"]))
            self.current = sprites.lock(data['name'], data['sprite'], eval(data['ob']), rep)

    def mouse(self, pos, button):
        xoff = 352 - self.cam.x*32
        yoff = 352 - self.cam.y*32
        x = (pos[0] - xoff)/32
        y = (pos[1] - yoff)/32

        if pygame.Rect(0,0,35,25).collidepoint(pos):
            """ TAB BACK """
            if self.tab > 0:
                self.tab -= 1
                vars.dung.change(self.tab)
                self.cam = Cam()
        elif pygame.Rect(22*32-135,0,45,25).collidepoint(pos):
            """ TAB NEXT """
            if self.tab < len(vars.dung.dungeons) - 1:
                self.tab += 1
                vars.dung.change(self.tab)
                self.cam = Cam()
        elif pygame.Rect(22*32-90,0,40,25).collidepoint(pos):
            """ TAB NEW """
            if self.tab == len(vars.dung.dungeons)-1: #bo zero
                vars.dung.dungeons.append(([[False]], vars.dung.floor))
                self.tab += 1
            else:
                vars.dung.dungeons.insert(self.tab, ([[False]], vars.dung.floor))
            vars.dung.change(self.tab)
            self.cam = Cam()
        elif pygame.Rect(22*32-50,0,50,25).collidepoint(pos):
            """ TAB DELETE """
            vars.dung.dungeons.pop(self.tab)
            if self.tab > 0:
                self.tab -= 1
                self.cam = Cam()
            elif len(vars.dung.dungeons) == 0:
                vars.dung.dungeons.append(([[False]], vars.dung.floor))
            vars.dung.change(self.tab)
        elif pygame.Rect(829, 674, 131, 30).collidepoint(pos):
            """ PANEL BUTTON QUIT """
            pygame.quit()
            sys.exit()
        elif pygame.Rect(829, 644, 131, 30).collidepoint(pos):
            """ PANEL BUTTON RELOAD """
            vars.dung = sprites.dungeon()
            vars.dung.regenerate()
        elif pygame.Rect(829, 614, 131, 30).collidepoint(pos):
            """ PANEL BUTTON SAVE """
            self.save()
        elif pygame.Rect(829-131, 614, 131, 30).collidepoint(pos):
            """ PANEL BUTTON EDIT OBJECT """
            self.setCurrent()
            self.gui.createWidgets(self.current)
        elif button == 3 and pygame.Rect(0, 25, 22*32, 22*32-25).collidepoint(pos):
            if x in range(len(vars.dung.dung[0])) and y in range(len(vars.dung.dung)):
                self.current = copy(vars.dung.get(x,y))
                if self.current:
                    if self.current.type == "bigSprite":
                        self.current = copy(vars.dung.get(self.current.parent.x,self.current.parent.y))
                self.gui.createWidgets(self.current)
        elif button == 1 and pygame.Rect(0, 25, 22*32, 22*32-25).collidepoint(pos):
            if x in range(len(vars.dung.dung[0])) and y in range(len(vars.dung.dung)):
                item = copy(self.current)
                try:
                    item.x
                except:
                    pass
                else:
                    item.x = x
                    item.y = y
                vars.dung.set(item, x, y)
                if item:
                    if item.type == "char":
                        size = img(item.sprite).get_size()
                        for yoff in range(size[1]/32):
                                for xoff in range(size[0]/32):
                                    if xoff or yoff:
                                        vars.dung.set(sprites.bigSprite(item, (x+xoff, y+yoff)), x+xoff, y+yoff)
        elif button == 2 and pygame.Rect(0, 25, 22*32, 22*32-25).collidepoint(pos):
            if x in range(len(vars.dung.dung[0])) and y in range(len(vars.dung.dung)):
                vars.dung.dung = vars.dung.dung[:y+1]
                for i in range(len(vars.dung.dung)):
                    vars.dung.dung[i] = vars.dung.dung[i][:x+1]
                vars.dung.dungeons[self.tab] = (vars.dung.dung, vars.dung.floor)
                vars.dung.regenerate()
            elif x > 0 and y > 0:
                addx = x - len(vars.dung.dung[0]) + 1
                addy = y - len(vars.dung.dung) + 1
                if addx < 0:
                    addx = 0
                if addy < 0:
                    addy = 0

                for row in vars.dung.dung:
                    for i in range(addx):
                        row.append(False)
                for i in range(addy):
                    vars.dung.dung.append([False]*len(vars.dung.dung[0]))
                vars.dung.regenerate()
                
    def tick(self):
        self.okienko.fill(colors.black)
        for x in range(22):
            for y in range(22):
                self.okienko.blit(img('mapEditBg'), (x*32,y*32))

        self.drawDung()
        self.drawTabs()
        self.drawPanel()
        self.gui.draw(self.okienko)
        pygame.display.update()
        
    def loop(self):
        while 1:
            self.events()
            self.tick()
            self.clock.tick(FPS)

if __name__ == "__main__": Editor()
